﻿using LD.Host;
using System;
using System.Diagnostics;
using System.IO.Ports;
using System.Text;
using System.Threading.Tasks;

namespace LD
{
    public class SerialHelper : BaseCommunication
    {
        private SerialPort _serialPort = null;
        private TcpIpParameModel _parame;
        public SerialHelper(TcpIpParameModel parame) : this(parame.Ip, parame.Port, parame.TimeOut, Parity.None, 8, StopBits.One)
        {
            _parame = parame;

        }
        public SerialHelper(string comPortName, int baudRate, int timeOut, Parity parity, int dataBits = 8, StopBits stopBits = StopBits.One)
        {
            if (_serialPort == null)
            {
                _serialPort = new SerialPort();
            }
            _serialPort.PortName = comPortName;
            _serialPort.BaudRate = baudRate;
            _serialPort.DataBits = dataBits;
            _serialPort.RtsEnable = true;
            _serialPort.DtrEnable = true;
            _serialPort.StopBits = stopBits;
            _serialPort.Parity = parity;
        }
        public override void Connect()
        {
            try
            {
                _serialPort.Open();
                ConnectionStateEvent?.Invoke(_parame.Name, Status.成功);
            }
            catch (Exception ex)
            {
                Log4.Info($"【{_parame.Name}】:{ex}");
                ConnectionStateEvent?.Invoke(_parame.Name, Status.失败);
            }
        }
        public override object Send(string content)
        {
            string resultMsg = string.Empty;
            try
            {
                if (!_serialPort.IsOpen)
                {
                    _serialPort.Open();
                }
                if (content.Length > 0)
                {
                    _serialPort.DiscardInBuffer();
                    _serialPort.Write(content);
                    Log4.Info($"【{_parame.Name}】发送:{content}");

                    byte[] reByte = ReceiveData();
                    resultMsg = BitConverter.ToString(reByte, 0, reByte.Length);
                }
            }
            catch (Exception ex)
            {
                Log4.Error($"【{_parame.Name}】发送:{content}," + ex.Message);
            }

            return resultMsg;
        }
        public override void Closed()
        {
            _serialPort?.Close();
        }
        public byte[] ReceiveData()
        {
            byte[] m_recvBytes = null;
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                while (_serialPort.BytesToRead == 0 &&
                    stopwatch.ElapsedMilliseconds < _parame.TimeOut
                    )
                {
                    Task.Delay(100).Wait();
                }
                if (_serialPort.BytesToRead > 0)
                {
                    m_recvBytes = new byte[_serialPort.BytesToRead]; //定义缓冲区大小  
                    int result = _serialPort.Read(m_recvBytes, 0, m_recvBytes.Length); //从串口读取数据  
                    string strResult = Encoding.UTF8.GetString(m_recvBytes, 0, m_recvBytes.Length); //对数据进行转换  
                }
            }
            catch (Exception ex)
            {
                Log4.Error($"【{_parame.Name}】" + ex.Message);
            }
            finally
            {
                stopwatch.Stop();
            }
            return m_recvBytes;
        }
    }
}
